import re
import urllib.parse
import requests
import time
class BuyTicket(object):
	# 买票成功的标志
    successFlag=False
    def __init__(self,stationDict,userproperties,stationTrainCodes,seatsIndex,smtpEmail):
    	self.userproperties=userproperties
    	self.stationDict=stationDict
    	self.stationTrainCodes=stationTrainCodes
    	self.seatsIndex=seatsIndex
    	self.smtpEmail=smtpEmail
    # 查票方法
    def checkTickets(self,session,train_date, from_station, to_station):
	    # 1、请求查票地址，赋予参数
	    checkTickets_url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=%s&' \
	                       'leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT' \
	                       % (train_date, self.stationDict[from_station], self.stationDict[to_station])
	    # print("查询车次信息接口",checkTickets_url)
	    checkTickets_res = session.get(checkTickets_url)
	    # 2、判断是否有车次
	    if len(checkTickets_res.text) > 0:
	        # 3、返回车次信息
	        # print("车次信息",checkTickets_res.text)
	        result={}
	        try:
	        	time.sleep(1)
	        	result = checkTickets_res.json()['data']['result']
	        	print("车次信息查询成功！")
	        except Exception as e:
	        	print(checkTickets_res)
	        	return self.checkTickets(session,train_date, from_station, to_station)
	        else:
	        	pass
	        finally:
	        	pass
	        return result
	    else:
	        print('车票查询失败，请重试！')
	        return self.checkTickets(session,train_date, from_station, to_station)

	# 买票方法
    def buyTicket(self,flag,session):
	    # train_date = '2019-01-14'
	    global successFlag
	    # train_date = '2019-01-14'
	    train_date=self.userproperties['train_date']
	    # from_station = '长沙'
	    # to_station = '武汉'
	    from_station = self.userproperties['from_station']
	    to_station = self.userproperties['to_station']
	    if len(flag) > 0:
	        # 车索引
	        station_index = 0
		        # 车次
	        stationStr = self.checkTickets(session,train_date, from_station, to_station)
	        print('当天有' + len(stationStr).__str__() + '趟车次')
	        while len(stationStr) >= station_index+1:
		        # print('当前车第'+int(station_index+1).__str__()+'辆')
		        stations = stationStr[station_index].split('|')
		        station_index = station_index+1
		        stationTrainCode=stations[3]
		        if stationTrainCode in self.stationTrainCodes:
		        	print("当前刷票车次",stationTrainCode)
		        else:
		        	# print("忽略",stationTrainCode,"继续刷票")
		        	continue
		        # 车编号
		        secretStr = urllib.parse.unquote(stations[0])
		        ticketNums=stations[30:33]
		        # 判断无票则进行下次循环
		        # print("票情况",ticketNums)
		        if '无' in ticketNums:
		        	print("当前车次无票")
		        	continue
		        # 根据预设的席别判断
		        if ticketNums[self.seatsIndex]=="无":
		        	print("所选席别无票")
		        	continue
		        else:
		        	print("所选席别票数",ticketNums[self.seatsIndex])
		        # 1、验证用户登录状态
		        check_user_url = 'https://kyfw.12306.cn/otn/login/checkUser'
		        session.post(check_user_url, data={'_json_att': ''})
		        # 2、提交订单请求
		        submit_order_url = 'https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest'
		        form_data = {
		            'back_train_date': '2018-10-29',
		            'purpose_codes': 'ADULT',
		            'query_from_station_name': from_station,
		            'query_to_station_name': to_station,
		            'secretStr': secretStr,
		            'tour_flag': 'dc',
		            'train_date': train_date,
		            'undefined': ''
		        }
		        submit_order_res = session.post(submit_order_url, data=form_data)
		        if submit_order_res.json()['status']:
		            # 3、初始化
		            init_dc_url = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
		            init_dc_res = session.post(init_dc_url, data={'_json_att': ''})
		            if len(init_dc_res.text) > 0:
		                print('初始化成功！')
		                # 4、获取初始化里面的隐藏参数
		                key_check_isChange = re.findall(r"'key_check_isChange':'(.*?)'", init_dc_res.text)[0]
		                # leftTicketStr = urllib.parse.quote(stations[12])
		                leftTicketStr = stations[12]
		                globalRepeatSubmitToken = re.findall(r"globalRepeatSubmitToken = '(.*?)'", init_dc_res.text)[0]
		                # stationTrainCode = stations[3]
		                train_location = stations[15]
		                train_no = stations[2]
		                # if len(key_check_isChange) > 0 & len(globalRepeatSubmitToken) > 0:
		                # 5、获取乘客信息
		                # get_passenger_url = 'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs'
		                # form_data = {
		                #     '_json_att': '',
		                #     'REPEAT_SUBMIT_TOKEN': globalRepeatSubmitToken
		                # }
		                # get_passenger_res = session.post(get_passenger_url, data=form_data)
		                # 存储乘客信息
		                # passengers_info = get_passenger_res.json()['data']['normal_passengers']
		                # 乘客索引
		                # passenger_index = 0
		                # 乘客姓名
		                # passenger_name = passengers_info[passenger_index]['passenger_name']
		                passenger_name=self.userproperties['passenger_name']
		                # 乘客身份证号
		                # passenger_id_no = passengers_info[passenger_index]['passenger_id_no']
		                passenger_id_no=self.userproperties['passenger_id_no']
		                # 乘客手机号
		                # mobile_no = passengers_info[passenger_index]['mobile_no']
		                mobile_no=self.userproperties['mobile_no']
		                # 6、检查订单信息
		                check_order_info_url = 'https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo'
		                # 座位等级，O二等座，M一等座，3硬卧，2软卧
		                # seats = 'M'
		                seats=self.userproperties['seats']
		                # 选座，ABC EF
		                # choose_seats = '1F'
		                choose_seats=self.userproperties['choose_seats']
		                # 乘客车票信息字符串
		                passengerTicketStr = seats+',0,1,' + passenger_name + ',1,' + passenger_id_no + ',' + mobile_no + ',N'
		                # 同上
		                oldPassengerStr = passenger_name + ',1,' + passenger_id_no + ',1_'
		                form_data = {
		                    '_json_att': '',
		                    'bed_level_order_num': '000000000000000000000000000000',
		                    'cancel_flag': '2',
		                    'oldPassengerStr': oldPassengerStr,
		                    'passengerTicketStr': passengerTicketStr,
		                    'randCode': '',
		                    'REPEAT_SUBMIT_TOKEN': globalRepeatSubmitToken,
		                    'tour_flag': 'dc',
		                    'whatsSelect': '1'
		                }
		                check_order_info_res = session.post(check_order_info_url, data=form_data)
		                if check_order_info_res.json()['status']:
		                    # 7、拿到票信息
		                    get_queue_count_url = 'https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount'
		                    form_data = {
		                        '_json_att': '',
		                        'fromStationTelecode': stations[4],
		                        'leftTicket': leftTicketStr,
		                        'purpose_codes': '00',
		                        'REPEAT_SUBMIT_TOKEN': globalRepeatSubmitToken,
		                        'seatType': seats,
		                        'stationTrainCode': stationTrainCode,
		                        'toStationTelecode': stations[5],
		                        'train_date': 'Sun Nov 11 2018 00:00:00 GMT+0800 (中国标准时间)',
		                        'train_location': train_location,
		                        'train_no': train_no
		                    }
		                    get_queue_count_res = session.post(get_queue_count_url, data=form_data)
		                    if get_queue_count_res.json()['status']:
		                        # 8、提交订单
		                        confirm_url = 'https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue'
		                        data = {
		                            'passengerTicketStr': passengerTicketStr,
		                            'oldPassengerStr': oldPassengerStr,
		                            'randCode': '',
		                            'purpose_codes': '00',
		                            'key_check_isChange': key_check_isChange,
		                            'leftTicketStr': leftTicketStr,
		                            'train_location': stations[15],
		                            'choose_seats': choose_seats,
		                            'seatDetailType': '000',
		                            'whatsSelect': '1',
		                            'roomType': '00',
		                            'dwAll': 'N',
		                            '_json_att': '',
		                            'REPEAT_SUBMIT_TOKEN': globalRepeatSubmitToken,
		                        }
		                        confirm_res = session.post(confirm_url, data=data)
		                        if confirm_res.json()['data']['submitStatus']:
		                            successFlag=True
		                            print('下单成功，请登录付款！')
		                            ret=self.smtpEmail.mail("您已经抢到一张火车票"+stationTrainCode+"，快去12306待支付订单页面付款吧",self.userproperties['email'])
		                            if ret:
		                                print("邮件发送成功")
		                            else:
		                                print("邮件发送失败")
		                            break
		                        else:
		                            print('下单失败，正在重试！')
		                            continue
		                    else:
		                        print('订单信息异常，正在重试！')
		                        continue
		                else:
		                    print('订单信息异常，正在重试！')
		                    continue
		            else:
		                print('初始化失败，正在重试！')
		                continue
		        else:
		            print('用户状态异常，正在重新登录！')
		            break